package com.ruoyi.framework.config;

import com.alibaba.cloud.spring.boot.sms.ISmsService;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.framework.config.properties.AlismsPropertis;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * 短信模板
 * 阿里云sms参考：https://help.aliyun.com/document_detail/55284.html
 *
 * @author dyun
 */
@Configuration
@ConditionalOnProperty(value = "alibaba.cloud.sms.enabled", matchIfMissing = true)
@EnableConfigurationProperties(AlismsPropertis.class)
public class AlismsConfig {

    private static AlismsPropertis alismsPropertis;

    private static ISmsService smsService;

    public AlismsConfig(AlismsPropertis alismsPropertis, ISmsService smsService) {
        AlismsConfig.smsService = smsService;
        AlismsConfig.alismsPropertis = alismsPropertis;
    }

    public static boolean sendMessage(SendSmsRequest sendSmsRequest) {
        try {
            SendSmsResponse sendSmsResponse = smsService.sendSmsRequest(sendSmsRequest);
            String successCode = "OK";
            if (sendSmsResponse != null && successCode.equals(sendSmsResponse.getCode())) {
                return true;
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 自动填充sms属性
     */
    public static boolean sendSignMessage(SendSmsRequest request) {
        request.setTemplateCode(alismsPropertis.getTemplate());
        //TODO 租户签名
        request.setSignName(alismsPropertis.getSign());
        return sendMessage(request);
    }
}
